package main

import (
	"encoding/json"
	"github.com/gorilla/mux"
	"io/ioutil"
	"net/http"
)

/*func MyGetHandler(w http.ResponseWriter, r *http.Request) {
	// parse query parameter
	vals := r.URL.Query() //获得请求参数
	//获得servicename对应的参数
	param, _ := vals["servicename"]  // get query parameters

	// composite response body构建响应体
	var res = map[string]string{"result":"succ", "name":param[0]}
	response, _ := json.Marshal(res)
	//设置头部
	w.Header().Set("Content-Type", "application/json")
	w.Write(response)//写入响应
}*/
func MyGetHandler(w http.ResponseWriter, r *http.Request) {
	var res map[string]string = make(map[string]string)
	var status = http.StatusOK

	vals := r.URL.Query()
	param, ok := vals["name"]
	if (!ok) {
		res["result"] = "fail"
		res["error"] = "required parameter name is missing"
		status = http.StatusBadRequest
	} else {
		res["result"] = "succ"
		res["name"] = param[0]
		status = http.StatusOK
	}

	response, _ := json.Marshal(res)
	w.WriteHeader(status)
	w.Header().Set("Content-Type", "application/json")
	w.Write(response)
}
func MyPostHandler(w http.ResponseWriter, r *http.Request) {
	// parse path variable
	vars := mux.Vars(r)
	servicename := vars["servicename"]
/**/
	// parse JSON body
	var req map[string]interface{}
	body, _ := ioutil.ReadAll(r.Body)
	//fmt.Println(r.Body)
	json.Unmarshal(body, &req)
	servicetype := req["servicetype"].(string)

	// composite response body
	var res = map[string]string{"result":"succ", "name":servicename, "type":servicetype}
	response, _ := json.Marshal(res)
	w.Header().Set("Content-Type", "application/json")
	w.Write(response)
}